import { createApp } from 'vue';
import ToastComponent from './toast.vue';

let instance = null;
let container = null;

export default {
  install(app) {
    const createToast = () => {
      if (!instance) {
        container = document.createElement('div');
        document.body.appendChild(container);
        instance = createApp(ToastComponent);
        instance = instance.mount(container);
      }
      return instance;
    };

    const toast = (msg, duraction = 1500, closeable) => {
      const toastInstance = createToast();
      if (toastInstance.visible) return;
      toastInstance.message = msg;
      toastInstance.visible = true;
      
      // 如果第二个参数是布尔值，则将其视为 closeable，duration 使用默认值
      if (typeof duraction === 'boolean') {
        toastInstance.closeable = duraction;
        // 即使 closeable 为 true，也设置自动关闭（5秒后）
        setTimeout(() => {
          toastInstance.visible = false;
        }, 5000);
      } else {
        // 如果第二个参数是数字，则作为 duration
        toastInstance.closeable = closeable || false;
        duraction = duraction || 1500;
        setTimeout(() => {
          toastInstance.visible = false;
        }, duraction);
      }
    };

    window.$toast = toast;
    app.config.globalProperties.$toast = toast;
  },
};
